<template>
  <el-container>
    <el-aside width="258px">
      <side_tree :data="ProList" :type="'porject'" :typeName="'项目管理'" :default="projectForm.projectId" v-on:childtofather="treeNode"
      />
    </el-aside>
    <el-main>
      <el-col :span="24" class="flex flex-justify clear" style="border-bottom: 1px solid #eee;padding-bottom: 10px">
        <!--名称-->
        <h1>{{projectForm.name}}</h1>
        <!--按钮-->
        <el-col :span="18" class="flex flex-right">
          <el-button size="small" v-if="roleIdList.includes(18)" type="warning" style="margin-right:20px" @click="openModal"><i class="fa fa-plus"></i> 创建项目</el-button>
          <el-button size="small" v-if="roleIdList.includes(19)" @click="chson('edit')" :disabled="!isUpdate" type="info">
            <i class="fa fa-edit"></i> 修改
          </el-button>
          <!-- <el-button size="small" type="danger" @click="del">
            <i class="fa fa-trash-o"></i>
            删除
          </el-button> -->
        </el-col>
      </el-col>
      <!--部门信息 表单-->
      <el-form :model="projectForm" ref="projectForm" :rules="rules" size="small" class="from-box" label-width="80px">
        <el-col :span="6">
          <el-form-item label="项目名称" prop="name">
            <el-input v-model="projectForm.name" size="small" :disabled="isUpdate"></el-input>
          </el-form-item>
          <el-form-item label="合同编号" prop="contractNumber">
            <el-input v-model="projectForm.contractNumber" disabled></el-input>
          </el-form-item>
          <el-form-item label="所属部门" prop="arrdeptId">
            <el-cascader v-model="projectForm.arrdeptId" :disabled="isUpdate" change-on-select :show-all-levels="false" :options="userDept"
              :props="{value: 'deptId',label: 'deptName'}" placeholder="请选择" style="width: 100%">
            </el-cascader>
          </el-form-item>
          <el-form-item label="施工单位" prop="constructDeptIds">
            <el-cascader v-model="projectForm.constructDeptIds" :disabled="isUpdate" change-on-select :show-all-levels="false" :options="userRealDept"
              :props="{value: 'deptId',label: 'deptName'}" placeholder="请选择" style="width: 100%">
            </el-cascader>
          </el-form-item>
          <el-form-item label="监理单位" prop="supervisorDeptIds">
            <el-cascader v-model="projectForm.supervisorDeptIds" :disabled="isUpdate" change-on-select :show-all-levels="false" :options="userRealDept"
              :props="{value: 'deptId',label: 'deptName'}" placeholder="请选择" style="width: 100%">
            </el-cascader>
          </el-form-item>
          <el-form-item label="检测单位" prop="detectionDeptIds">
            <el-cascader v-model="projectForm.detectionDeptIds" :disabled="isUpdate" change-on-select :show-all-levels="false" :options="userRealDept"
              :props="{value: 'deptId',label: 'deptName'}" placeholder="请选择" style="width: 100%">
            </el-cascader>
          </el-form-item>
          <el-form-item label="施工区域" prop="area">
            <el-input v-model.trim="projectForm.area" :disabled="isUpdate"></el-input>
          </el-form-item>
          <el-form-item label="项目时间" prop="contractDate">
            <el-date-picker v-model.number="projectForm.contractDate" type="datetime" start-placeholder="开始时间" style="width: 100%" :disabled="isUpdate">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="结束时间" prop="contractEnd">
            <el-date-picker v-model.number="projectForm.contractEnd" type="datetime" start-placeholder="结束时间" style="width: 100%" :disabled="isUpdate">
            </el-date-picker>
          </el-form-item>
          <!-- <el-form-item label="状态" prop="status">
            <el-select v-model="projectForm.status" placeholder="请选择" style="width: 100%" disabled>
              <el-option v-for="item in treeData" :key="item.id" :label="item.label" :value="item.groupId">
              </el-option>
            </el-select>
          </el-form-item> -->
        </el-col>
        <el-col :span="24" class="flex flex-justify clear" v-if="show" style="border-top: 1px solid #eee;padding-top: 20px">
          <!--按钮-->
          <el-col :span="18" class="flex flex-left">
            <el-button size="small" @click="chson('save')" type="primary">
              <i class="fa fa-save"></i> 保存
            </el-button>
            <el-button size="small" @click="chson('cancel')">
              <i class="fa fa-trash-o"></i> 取消</el-button>
          </el-col>
        </el-col>
      </el-form>
      <el-col :span="24">
      </el-col>
    </el-main>
    <AddModal :addModal="addModal" :treeData="userDept" :realTreeData="userRealDept" @closeModal="closeModal" @addFinish="addFinish"
    />
  </el-container>
</template>
<script>
  import side_tree from "../aside";
  import AddModal from "./addModal";
  import ElCol from "element-ui/packages/col/src/col";
  import {
    formCheck,
    trim,
    deepClone
  } from "../../../lib/utils";
  import {
    projectManagement
  } from "../../../service/service_zbw";
  import {
    mapState,
    mapMutations
  } from "vuex";
  export default {
    components: {
      //创建树组件
      ElCol,
      side_tree,
      AddModal
    },
    data() {
      const checkTime = (rule, value, callback) => {
        if (!value) {
          return callback(new Error('请选择项目开始时间'));
        } else {
          if (this.projectForm.contractEnd !== '' && this.projectForm.contractEnd <= value) {
            return callback(new Error('项目开始时间必须在项目结束时间之前'));
          }
          callback();
        }
      };
      const checkEndTime = (rule, value, callback) => {
        if (!value) {
          return callback(new Error('请选择项目结束时间'));
        } else {
          if (this.projectForm.contractDate !== '' && this.projectForm.contractDate >= value) {
            return callback(new Error('项目结束时间必须在项目开始时间之后'));
          }
          callback();
        }
      };
      return {
        //判断是否是编辑
        isUpdate: true,
        show: false,
        //侧栏树组件的数据
        ProList: [],
        projectForm: {
          name: '',
          contractNumber: '',
          arrdeptId: [],
          constructDeptIds: [],
          supervisorDeptIds: [],
          detectionDeptIds: [],
          area: '',
          contractDate: '',
          contractEnd: '',
          status: ''
        },
        copyProjectForm: {},
        rules: {
          name: [{
              required: true,
              message: '请输入项目名称',
              trigger: 'blur'
            },
            {
              min: 1,
              max: 10,
              message: '长度不能超过10个字符',
              trigger: 'blur'
            }
          ],
          contractNumber: [{
              required: true,
              message: '请输入合同编号',
              trigger: 'blur'
            },
            {
              min: 1,
              max: 50,
              message: '长度不能超过50个字符',
              trigger: 'blur'
            }
          ],
          area: [{
              required: true,
              message: '请输入施工区域',
              trigger: 'blur'
            },
            {
              min: 1,
              max: 50,
              message: '长度不能超过50个字符',
              trigger: 'blur'
            }
          ],
          arrdeptId: [{
            type: 'array',
            required: true,
            message: '请选择所属部门',
            trigger: 'blur'
          }],
          constructDeptIds: [{
            type: 'array',
            required: true,
            message: '请选择施工单位',
            trigger: 'blur'
          }],
          supervisorDeptIds: [{
            type: 'array',
            required: true,
            message: '请选择监理单位',
            trigger: 'blur'
          }],
          detectionDeptIds: [{
            type: 'array',
            required: true,
            message: '请选择检测单位',
            trigger: 'blur'
          }],
          contractDate: [{
            type: 'date',
            required: true,
            validator: checkTime,
            trigger: 'change'
          }],
          contractEnd: [{
            type: 'date',
            required: true,
            validator: checkEndTime,
            trigger: 'change'
          }],
        },
        addModal: false,
        status: {

        }
      }
    },
    computed: {
      ...mapState({
        userDept: state => state.userDept,
        userRealDept: state => state.userRealDept,
        roleIdList: state => state.roleIdList,
        menuList: state => state.menuList,
      })
    },
    methods: {
      ...mapMutations([
        'SET_MENULIST'
      ]),
      openModal() {
        this.addModal = true;
        this.isUpdate = true;
        this.show = false;
      },
      /**@function
       * 获取项目列表
       */
      async getProList() {
        let res = await projectManagement.getProList();
        if (res.success) {
          this.ProList = res.obj;
          for (let i of this.ProList) {
            i.id = i.projectId;
            i.area = i.area || '';
          }
          this.projectForm = deepClone(this.ProList[0]);
          this.projectForm.contractDate = new Date(this.projectForm.contractDate);
          this.projectForm.contractEnd = new Date(this.projectForm.contractEnd);
        } else {
          this.ProList = [];
        }
      },
      //接收树组件传递过来的数据，obj是节点对象
      treeNode(obj) {
        console.log(obj)
        //赋值给data
        this.projectForm = deepClone(obj);
        this.projectForm.contractDate = new Date(this.projectForm.contractDate);
        this.projectForm.contractEnd = new Date(this.projectForm.contractEnd);
      },
      //编辑，保存，修改
      async chson(val) {
        if (val == 'save') {
          let flag = formCheck(this, 'projectForm');
          if (flag) {
            let param = {
              projectId: this.projectForm.projectId,
              area: this.projectForm.area,
              constructDeptId: this.projectForm.constructDeptIds[this.projectForm.constructDeptIds.length - 1],
              contractDate: this.projectForm.contractDate,
              contractEnd: this.projectForm.contractEnd,
              contractNumber: this.projectForm.contractNumber,
              deptId: this.projectForm.arrdeptId[this.projectForm.arrdeptId.length - 1],
              detectionDeptId: this.projectForm.detectionDeptIds[this.projectForm.detectionDeptIds.length - 1],
              name: this.projectForm.name,
              supervisorDeptId: this.projectForm.supervisorDeptIds[this.projectForm.supervisorDeptIds.length - 1]
            };
            let res = await projectManagement.update(param);
            if (res.success) {
              let obj = this.menuList;
              for (let i of obj) {
                if (i.id === 48) {
                  for (let j of i.children) {
                    j.label = this.projectForm.name;
                    break;
                  }
                  break;
                }
              }
              this.SET_MENULIST(obj);
              this.getProList();
              this.$message({
                message: res.msg,
                type: 'success'
              });
              this.isUpdate = !this.isUpdate;
              this.show = !this.show;
            } else {
              this.$message({
                message: res.msg,
                type: 'error'
              });
            }
          }
        } else {
          if (val == 'edit') {
            // this.copyProjectForm = deepClone(this.projectForm);
            this.copyProjectForm = {
              name: this.projectForm.name,
              contractNumber: this.projectForm.contractNumber,
              arrdeptId: this.projectForm.arrdeptId,
              constructDeptIds: this.projectForm.constructDeptIds,
              supervisorDeptIds: this.projectForm.supervisorDeptIds,
              detectionDeptIds: this.projectForm.detectionDeptIds,
              area: this.projectForm.area,
              contractDate: this.projectForm.contractDate,
              contractEnd: this.projectForm.contractEnd,
            };
          } else {
            this.handleReset('projectForm');
            // this.projectForm = deepClone(this.copyProjectForm);
            this.projectForm = {
              name: this.copyProjectForm.name,
              contractNumber: this.copyProjectForm.contractNumber,
              arrdeptId: this.copyProjectForm.arrdeptId,
              constructDeptIds: this.copyProjectForm.constructDeptIds,
              supervisorDeptIds: this.copyProjectForm.supervisorDeptIds,
              detectionDeptIds: this.copyProjectForm.detectionDeptIds,
              area: this.copyProjectForm.area,
              contractDate: this.copyProjectForm.contractDate,
              contractEnd: this.copyProjectForm.contractEnd,
            };
          }
          this.projectForm.contractDate = new Date(this.projectForm.contractDate);
          this.projectForm.contractEnd = new Date(this.projectForm.contractEnd);
          this.isUpdate = !this.isUpdate;
          this.show = !this.show;
        }
      },
      addFinish(val) {
        let obj = this.menuList;
        for (let i of obj) {
          if (i.id === 48) {
            let item = {
              id: val.projectId,
              label: val.name,
              menuUrl: `/index/construction/${val.projectId}`
            };
            i.children.unshift(item);
            break;
          }
        }
        this.SET_MENULIST(obj);
        this.getProList();
      },
      //删除
      //   del(id, label) {
      //     this.$confirm('您确定要删除部门“' + label + '”吗？', '询问', {
      //       confirmButtonText: '确定',
      //       cancelButtonText: '取消',
      //       type: 'warning',
      //       center: true
      //     }).then(() => {
      //       this.$message({
      //         type: 'success',
      //         message: '删除成功!'
      //       });
      //     }).catch(() => {
      //       //TODO
      //     });
      //   },
      /**
       * 关闭模态框
       */
      closeModal(val) {
        this.addModal = val;
      },
      /**
       * 清空表单
       */
      handleReset(name) {
        this.$refs[name].resetFields();
      }
    },
    watch: {
      "projectForm.projectId" (newval, oldval) {
        this.handleReset('projectForm');
        this.isUpdate = true;
        this.show = false;
      }
    },
    mounted() {
      this.getProList();
    }
  }

</script>

<style scoped>
  h1 {
    width: 25%;
    font-weight: bold;
    color: #666666;
    font-size: 18px;
  }

</style>

